package com.rancedxk.monitor.api.impl;

import java.util.HashMap;
import java.util.Map;

import com.rancedxk.monitor.api.IApi;
import com.rancedxk.monitor.lib.UniViewNetSDK;
import com.rancedxk.monitor.task.AutoStopInvoker;
import com.rancedxk.monitor.task.AutoStopTaskManager;
import com.rancedxk.monitor.utils.Kv;

public class UniViewApi implements IApi{
	/**用户登录句柄缓存，理论上只要jvm不重启，每一个IP的命令句柄是可以保存使用的，所以此处缓存起来*/
	static Map<String,Integer> LOGIN_USER_HANDLE_CACHE = new HashMap<String,Integer>();

	//设备全局初始化
	static {
		UniViewNetSDK.INSTANCE.NETDEV_Init();
	}

	@Override
	public int login(String code, String ip, String username, String password, int port) {
		if(LOGIN_USER_HANDLE_CACHE.containsKey(code)){
			return LOGIN_USER_HANDLE_CACHE.get(code);
		}
		//设备登录信息
		UniViewNetSDK.NETDEV_DEVICE_INFO_S deviceInfo = new UniViewNetSDK.NETDEV_DEVICE_INFO_S();
		deviceInfo.dwDevType = UniViewNetSDK.NETDEV_DEVICE_TYPE_E.NETDEV_DTYPE_UNKNOWN;
		deviceInfo.dwAlarmInPortNum = 1;
		deviceInfo.dwAlarmOutPortNum = 1;
		deviceInfo.dwChannelNum = 1;
		deviceInfo.write();
		// 注册设备-登录参数，包括设备地址、登录用户、密码等,输出参数
		int lpUserID = UniViewNetSDK.INSTANCE.NETDEV_Login(ip, (short) port, username, password, deviceInfo);
		if(lpUserID < 0){
			UniViewNetSDK.INSTANCE.NETDEV_Cleanup();
			return -1;
		}
		LOGIN_USER_HANDLE_CACHE.put(code, lpUserID);
		return lpUserID;
	}

	/**
	 * 将统一命令字符转换为海康SDK能识别的int类型命令字
	 * @param commandStr 命令字符串
	 * @return int类型的命令字
	 */
	private static Map<String,Integer> COMMANDS = new HashMap<String,Integer>(){
		private static final long serialVersionUID = 1L;
		{
			put("FOCUS_NEAR", 0x0302); //焦距放大
			put("FOCUS_FAR", 0x0304); //焦距缩小
			put("TILT_UP", 0x0402);	// 云台上仰
			put("TILT_DOWN", 0x0404);	// 云台下俯
			put("PAN_LEFT", 0x0504);// 云台左转
			put("PAN_RIGHT", 0x0502);	// 云台右转
			put("UP_LEFT", 0x0702);	// 云台左转上仰
			put("UP_RIGHT", 0x0802);	// 云台右转上仰
			put("DOWN_LEFT", 0x0704);	// 云台左转下俯
			put("DOWN_RIGHT", 0x0804);// 云台右转下俯
			put("MOVE_STOP", 0x0901);// 云台移动停止
		}
	};

	@Override
	public boolean control(String code, int loginUserHandle, String command, Kv params) {
		if(AutoStopTaskManager.isContain(code)){
			AutoStopTaskManager.get(code).spirit();
		}else{
			AutoStopTaskManager.create(code, new AutoStopInvoker() {
				@Override
				public void onStart() {
					UniViewNetSDK.INSTANCE.NETDEV_PTZControl_Other(loginUserHandle, params.getInt("channel"), COMMANDS.get(command), params.getInt("speed"));
				}
				@Override
				public void onStop() {
					UniViewNetSDK.INSTANCE.NETDEV_PTZControl_Other(loginUserHandle, params.getInt("channel"), COMMANDS.get("MOVE_STOP"), params.getInt("speed"));
				}
			}, 1000);
		}
		return true;
	}

	public static void main(String[] args) {

	}
}
